<?php

namespace app\api\controller;

use app\common\controller\Api;
use  think\Db;
use think\Env;
use fast\Random;

/**
 * 医护端接口
 */
class Info extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $redis;
    private $url;
    private $user_arr;

    public function _initialize()
    {
        parent::_initialize();

        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
        $this->url = Env::get('url.url');

        $token = empty($_SERVER['HTTP_TOKEN']) ? $this->error('token不能为空',[],'401'):$_SERVER['HTTP_TOKEN'];//获取token
        $this->user_arr = json_decode($this->redis->Get('luying:token:'.$token),true);//设置redis

        if (empty($this->user_arr)){
            $this->error('用户信息为空',[],'401');
        }
    }

    /**
     *个人中心接口
     *
     */
    public function user_info(){
        $data = Db::table('fa_medic')
            ->field('id,name,image,phone,type,username,password')
            ->where('id',$this->user_arr['id'])
            ->find();

        $data['image'] = $this->url.$data['image'];

        $this->success('查询成功',$data);
    }

    /**
     * 修改密码
     *
     */
    public function change_password(){
        $password = empty(request()->post('password')) ? $this->error('password不能为空'):request()->post('password');

        $update = Db::table('fa_medic')
            ->where('id',$this->user_arr['id'])
            ->update([
                'password' => $password,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }


    /**
     *预约挂号列表数据
     *
     */
    public function get_registration(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $code = empty(request()->post('code')) ? '':request()->post('code');
        $name = empty(request()->post('name')) ? '':request()->post('name');
        $project = empty(request()->post('project')) ? '':request()->post('project');
        $status = empty(request()->post('status')) ? '':request()->post('status');
        $begin_time = empty(request()->post('begin_time')) ? '':request()->post('begin_time');
        $end_time = empty(request()->post('end_time')) ? '':request()->post('end_time');
        $medic_id = empty(request()->post('medic_id')) ? '':request()->post('medic_id');


        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($code)){
            $where['a.code'] = ['like','%'.$code.'%'];
        }

        if (!empty($name)){
            $where['b.name'] = $name;
        }

        if (!empty($project)){
            $where['a.project'] = ['like','%'.$project.'%'];
        }

        if (!empty($status)){
            $where['a.status'] = $status;
        }

        if (!empty($medic_id)){
            $where['a.medic_id'] = $medic_id;
        }

        if (!empty($begin_time)){
            $where['a.begin_time'] = ['>=',strtotime($begin_time)];
        }

        if (!empty($end_time)){
            $where['a.end_time'] = ['<=',strtotime($end_time)];
        }


        $data = Db::table('fa_registration')
            ->alias('a')
            ->field('a.id,a.code,b.name,b.sex,b.birthday,b.mobile,a.project,a.price,a.visiting_time,a.create_time,a.status,a.info_id,b.status as statuss')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where($where)
            ->limit($page_start,$limt)
            ->order('id','desc')
            ->select();

        $total = Db::table('fa_registration')
            ->alias('a')
            ->field('a.id,b.name,b.sex,b.birthday,b.mobile,a.project,a.price,a.create_time,status')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where($where)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['price'] = $v['price']/100;
                $data[$k]['age'] = countage($v['birthday']);
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                unset($data[$k]['birthday']);
                if ($v['status'] == '待就诊'){
                    $data[$k]['status'] = '待咨询';
                }
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);

    }

    /**
     *预约挂号详情
     *
     */
    public function registration_details(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');


        $data = Db::table('fa_registration')
            ->alias('a')
            ->field('a.id,a.code,a.create_time,a.project,a.visiting_time,b.name,c.name as names,c.sex,c.birthday,c.mobile,c.address,a.status,a.info_id,a.msg,c.status as statuss')
            ->join('fa_medic b','a.medic_id=b.id','left')
            ->join('fa_info c','a.info_id=c.id','left')
            ->where('a.id',$id)
            ->find();

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
        $data['age'] = countage($data['birthday']);
        if ($data['status'] == '待就诊'){
            $data['status'] = '待咨询';
        }


        $this->success('成功',$data);

    }

    /**
     *
     * 转诊
     */
    public function change(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $working_id = empty(request()->post('working_id')) ? $this->error('working_id不能为空'):request()->post('working_id');

        $pan = Db::table('fa_registration')
            ->where('working_id',$working_id)
            ->find();
        if (!empty($pan)){
            $this->error('该时间段已被预约',[]);
        }

        $data_working = Db::table('fa_working')
            ->where('id',$working_id)
            ->find();

        if (empty($data_working)){
            $this->error('预约时间不存在',[]);
        }

        switch ($data_working['time']){
            case 1:
                if (date('Y-m-d H:i:s') > $data_working['date'].' 10:00:00'){
                    $this->error('预约时间已超时');
                }
                break;
            case 2:
                if (date('Y-m-d H:i:s') > $data_working['date'].' 11:00:00'){
                    $this->error('预约时间已超时');
                }
                break;
            case 3:
                if (date('Y-m-d H:i:s') > $data_working['date'].' 12:00:00'){
                    $this->error('预约时间已超时');
                }
                break;
            case 4:
                if (date('Y-m-d H:i:s') > $data_working['date'].' 15:00:00'){
                    $this->error('预约时间已超时');
                }
                break;
            case 5:
                if (date('Y-m-d H:i:s') > $data_working['date'].' 16:00:00'){
                    $this->error('预约时间已超时');
                }
                break;
            case 6:
                if (date('Y-m-d H:i:s') > $data_working['date'].' 17:00:00'){
                    $this->error('预约时间已超时');
                }
                break;
            default:
                $this->error('预约时间错误');
                break;
        }

        //订单支付
        if (empty($data_working)){
            $visiting_time = '';
            $datess = '';
        }else{
            $date = date("w",strtotime($data_working['date']));

            switch ($data_working['time']){
                case 1:
                    $tims = '09:00-10:00';
                    break;
                case 2:
                    $tims = '10:00-11:00';
                    break;
                case 3:
                    $tims = '11:00-12:00';
                    break;
                case 4:
                    $tims = '14:00-15:00';
                    break;
                case 5:
                    $tims = '15:00-16:00';
                    break;
                case 6:
                    $tims = '16:00-17:00';
                    break;
            }

            switch ($date){
                case 0:
                    $day = '星期天';
                    break;
                case 1:
                    $day = '星期一';
                    break;
                case 2:
                    $day = '星期二';
                    break;
                case 3:
                    $day = '星期三';
                    break;
                case 4:
                    $day = '星期四';
                    break;
                case 5:
                    $day = '星期五';
                    break;
                case 6:
                    $day = '星期六';
                    break;
                default:
                    $day = '';
                    break;
            }

            $timss = explode('-',$tims);

            $visiting_time = $data_working['date'].' '.$day.' '.$tims;
            $datess = $data_working['date'];
            $begin_time = strtotime($data_working['date'].' '.$timss[0]);
            $end_time = strtotime($data_working['date'].' '.$timss[1]);
        }


        $update = Db::table('fa_registration')
            ->where('id',$id)
            ->update([
                'medic_id' => $data_working['medic_id'],
                'visiting_time' => $visiting_time,
                'begin_time' => $begin_time,
                'end_time' => $end_time,
                'date' => $datess,
                'working_id' => $working_id,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功');
        }else{
            $this->error('失败');
        }

    }

    /**
     * 新增病历模板
     *
     */
    public function add_medical(){
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');
        $disease_ids = empty(request()->post('disease_ids')) ? $this->error('disease_ids不能为空'):request()->post('disease_ids');
        $disease_name = empty(request()->post('disease_name')) ? $this->error('disease_name不能为空'):request()->post('disease_name');
        $appeal = empty(request()->post('appeal')) ? '':request()->post('appeal');
        $now = empty(request()->post('now')) ? '':request()->post('now');
        $before = empty(request()->post('before')) ? '':request()->post('before');
        $physique = empty(request()->post('physique')) ? $this->error('physique不能为空'):request()->post('physique');
        $diagnose = empty(request()->post('diagnose')) ? $this->error('diagnose不能为空'):request()->post('diagnose');
        $treatment = empty(request()->post('treatment')) ? $this->error('treatment不能为空'):request()->post('treatment');
        $announcements = empty(request()->post('announcements')) ? $this->error('announcements不能为空'):request()->post('announcements');
        $msg = empty(request()->post('msg')) ? '':request()->post('msg');


        $insert = Db::table('fa_medical_templates')
            ->insertGetId([
                'medic' => $this->user_arr['id'],
                'name' => $name,
                'disease_ids' => $disease_ids,
                'disease_name' => $disease_name,
                'appeal' => $appeal,
                'now' => $now,
                'before' => $before,
                'physique' => $physique,
                'diagnose' => $diagnose,
                'treatment' => $treatment,
                'announcements' => $announcements,
                'msg' => $msg,
                'create_time' => time(),
            ]);

        if ($insert > 0){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }

    /**
     * 病历模板列表
     *
     */
    public function get_medical(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数


        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $data = Db::table('fa_medical_templates')
            ->field('id,name,disease_name,create_time')
            ->where('medic',$this->user_arr['id'])
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_medical_templates')
            ->where('medic',$this->user_arr['id'])
            ->count();


        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }


    /**
     * 病历模板详情
     *
     */
    public function medical_details(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_medical_templates')
            ->where('id',$id)
            ->find();

        if (!empty($data)){
            $data['disease_ids'] = explode(',',$data['disease_ids']);
        }

        $this->success('查询成功',$data);
    }

    /**
     * 新增诊疗项目
     *
     */
    public function add_diagnosis(){
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');
        $disease_ids = empty(request()->post('disease_ids')) ? $this->error('disease_ids不能为空'):request()->post('disease_ids');
        $disease_name = empty(request()->post('disease_name')) ? $this->error('disease_name不能为空'):request()->post('disease_name');
        $data = empty(input('post.data/a')) ? $this->error('data不能为空'):input('post.data/a');

        if (!is_array($data)){
            $this->error('模板数据不是数组');
        }

        //开启事务
        Db::startTrans();
        $insert = Db::table('fa_template')
            ->insertGetId([
                'medic_id'=> $this->user_arr['id'],
                'name'=> $name,
                'disease_ids'=> $disease_ids,
                'disease_name'=> $disease_name,
                'create_time'=> time(),
                'type'=> 1,
            ]);

        foreach ($data as $k=>$v){
            $update = Db::table('fa_diagnosis_template')
                ->insertGetId([
                    'template_id' => $insert,
                    'diagnosis_id' => $v['diagnosis_id'],
                    'diagnosis_name' => $v['diagnosis_name'],
                    'specification' => $v['specification'],
                    'count' => $v['counts'],
                    'unit' => $v['unit'],
                    'msg' => $v['msg'],
                    'create_time' => time(),
                ]);

            if (($insert < 1) && ($update < 1)){
                //事务回滚
                Db::rollback();
                $this->error('失败');
            }
        }


        //事务提交
        Db::commit();
        $this->success('成功');

    }


    /**
     * 新增药品模板
     *
     */
    public function add_drug(){
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');
        $disease_ids = empty(request()->post('disease_ids')) ? '':request()->post('disease_ids');
        $disease_name = empty(request()->post('disease_name')) ? '':request()->post('disease_name');
        $data = empty(input('post.data/a')) ? $this->error('data不能为空'):input('post.data/a');

        if (!is_array($data)){
            $this->error('模板数据不是数组');
        }

        //开启事务
        Db::startTrans();
        $insert = Db::table('fa_template')
            ->insertGetId([
                'medic_id'=> $this->user_arr['id'],
                'name'=> $name,
                'disease_ids'=> $disease_ids,
                'disease_name'=> $disease_name,
                'create_time'=> time(),
                'type'=> 2,
            ]);

        foreach ($data as $k=>$v){
            $update = Db::table('fa_drug_template')
                ->insertGetId([
                    'template_id' => $insert,
                    'medicine_id' => $v['medicine_id'],
                    'medicine_name' => $v['medicine_name'],
                    'specification' => $v['specification'],
                    'count' => $v['counts'],
                    'unit' => $v['unit'],
                    'msg' => $v['msg'],
                    'create_time' => time(),
                ]);

            if (($insert < 1) && ($update < 1)){
                //事务回滚
                Db::rollback();
                $this->error('失败');
            }
        }


        //事务提交
        Db::commit();
        $this->success('成功');

    }



    /**
     * 诊疗项目/药品模板列表
     *
     */
    public function diagnosis_drug(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数


        //type为1代表诊疗，2为药品
        if (!in_array($type,[1,2])){
            $this->error('type参数错误');
        }

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }


        $data = Db::table('fa_template')
            ->field('id,name,disease_name,create_time')
            ->where(['medic_id'=>$this->user_arr['id'],'type'=>$type])
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_template')
            ->where(['medic_id'=>$this->user_arr['id'],'type'=>$type])
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }


    /**
     * 诊疗项目/药品模板详情
     *
     */
    public function diagnosis_drugs(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_template')
            ->where('id',$id)
            ->find();

        if (!empty($data)){

            if ($data['type'] == 1){
                $arr = Db::table('fa_diagnosis_template')
                    ->alias('a')
                    ->field('a.id,a.diagnosis_id as ids,a.diagnosis_name as name,a.specification,a.count as counts,a.unit,a.msg,b.price')
                    ->join('fa_diagnosis b','a.diagnosis_id=b.id','left')
                    ->where('a.template_id',$data['id'])
                    ->select();
            }elseif ($data['type'] == 2){
                $arr = Db::table('fa_drug_template')
                    ->field('id,medicine_id as ids,medicine_name as name,specification,count as counts,unit,msg')
                    ->where('template_id',$data['id'])
                    ->select();


                foreach ($arr as $k=>$v){
                    $find = Db::table('fa_storage')
                        //->where(['medicine_id'=>$v['ids'],'quantity'=>['<>',0]])
                        ->where(['id'=>$v['ids'],'quantity'=>['<>',0]])
                        ->order(['end_time'=>'asc','id'=>'desc'])
                        ->find();

                    if (empty($find)){
                        $arr[$k]['sell'] = 0;
                    }else{
                        $arr[$k]['sell'] = $find['sell'];
                    }
                }

            }

        }

        $this->success('查询成功',$arr);
    }

    /**
     *
     * 病历模板删除
     */
    public function del_medical(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $del = Db::table('fa_medical_templates')
            ->where('id',$id)
            ->delete();

        if ($del !== false){
            $this->success('成功');
        }else{
            $this->success('失败');
        }
    }

    /**
     * 删除诊疗项目/药品模板
     *
     */
    public function del_template(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_template')
            ->where('id',$id)
            ->find();

        //开启事务
        Db::startTrans();
        if (!empty($data)){
            if ($data['type'] == 1){
                $dels = Db::table('fa_diagnosis_template')
                    ->where('template_id',$data['id'])
                    ->delete();
            }elseif ($data['type'] == 2){
                $dels = Db::table('fa_drug_template')
                    ->where('template_id',$data['id'])
                    ->delete();
            }

            $del = Db::table('fa_template')
                ->where('id',$id)
                ->delete();

        }else{
            $this->error('模板数据为空');
        }


        if (($dels !== false) && ($del !== false)){
            //提交事务
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }

    }

    /**
     *
     *接诊接口
     */
    public function clinical_reception(){
        $id = empty(request()->post('id')) ? '':request()->post('id');
        $arr = empty(input('post.arr/a')) ? $this->error('arr不能为空'):input('post.arr/a');

        if (empty($arr['physique'])){
            $this->error('体格信息不能为空');
        }

        if (empty($arr['medical'])){
            $this->error('病历信息不能为空');
        }

        if (empty($arr['other'])){
            $this->error('其他信息不能为空');
        }

        if (empty($arr['diagnosis'])){
            $this->error('诊疗单信息不能为空');
        }

//        if (empty($arr['drug'])){
//            $this->error('药品单信息不能为空');
//        }

        if (empty($arr['course'])){
            $this->error('疗程信息不能为空');
        }

        if (empty($arr['diagnosis_msgs'])){
            $diagnosis_msgs = '';
        }else{
            $diagnosis_msgs = $arr['diagnosis_msgs'];
        }

        if (empty($arr['drug_msgs'])){
            $drug_msgs = '';
        }else{
            $drug_msgs = $arr['drug_msgs'];
        }


        $code = get_strings(8,2);

        $info_arr = Db::table('fa_info')
            ->where('id',$arr['other']['info_id'])
            ->find();

        if (empty($info_arr)){
            $this->error('就诊人数据为空');
        }

        if ($info_arr['status'] == 1){
            $this->error('预约用户不能接诊');
        }

        //开启事务
        Db::startTrans();

        //新增诊疗订单表
        $insert = Db::table('fa_diagnosis_order')
            ->insertGetId([
                'code' => $code,
                'info_id' => $arr['other']['info_id'],
                'medic_id' => $this->user_arr['id'],
                'medic_name' => $this->user_arr['name'],
                'height' => $arr['physique']['height'],
                'weight' => $arr['physique']['weight'],
                'blood_pressure' => $arr['physique']['blood_pressure'],
                'sphygmus' => $arr['physique']['sphygmus'],
                'disease_ids' => $arr['other']['disease_ids'],
                'disease_name' => $arr['other']['disease_name'],
                'appeal' => $arr['medical']['appeal'],
                'now' => $arr['medical']['now'],
                'before' => $arr['medical']['before'],
                'physique' => $arr['medical']['physique'],
                'diagnose' => $arr['medical']['diagnose'],
                'treatment' => $arr['medical']['treatment'],
                'announcements' => $arr['medical']['announcements'],
                'msg' => $arr['medical']['msg'],
                'remote_views' => $arr['medical']['remote_views'],
                'create_time' => time(),
                'type' => $arr['other']['type'],
                'diagnosis_cost' => $arr['other']['diagnosis_cost'],
                'drugs_cost' => $arr['other']['drugs_cost'],
                'vip_cost' => $arr['other']['vip_cost'],
                'count_cost' => $arr['other']['count_cost'],
                'symptom' => $arr['other']['symptom'],
                'health_money' => $arr['other']['health_money'],
                'diagnosis_msgs' => $diagnosis_msgs,
                'drug_msgs' => $drug_msgs,
            ]);

        //组装诊疗单数据
        foreach ($arr['diagnosis'] as $k=>$v){
            $diagnosis[$k]['order_id'] = $insert;
            $diagnosis[$k]['diagnosis_id'] = $v['id'];
            $diagnosis[$k]['diagnosis_name'] = $v['name'];
            $diagnosis[$k]['specification'] = $v['specification'];
            $diagnosis[$k]['count'] = $v['counts'];
            $diagnosis[$k]['unit'] = $v['unit'];
            $diagnosis[$k]['msg'] = $v['msg'];
            $diagnosis[$k]['price'] = $v['price'];
            $diagnosis[$k]['total'] = $v['price']*$v['counts'];
            $diagnosis[$k]['create_time'] = time();
        }

        //组装疗程数据
        foreach ($arr['course'] as $k=>$v){
            $course[$k]['order_id'] = $insert;
            $course[$k]['info_id'] = $arr['other']['info_id'];
            $course[$k]['name'] = '第'.($k+1).'次';
            $course[$k]['date'] = $v['date'];
            $course[$k]['create_time'] = time();
        }

        //新增诊疗单表
        $insert_diagnosis = Db::table('fa_diagnosiss')
            ->insertAll($diagnosis);

        //新增疗程表
        $insert_course = Db::table('fa_treatment')
            ->insertAll($course);

        //判断药品数据是否为空
        if (!empty($arr['drug'])){
            //组装药品单数据
            foreach ($arr['drug'] as $k=>$v){
                $drug[$k]['order_id'] = $insert;
                $drug[$k]['medicine_id'] = $v['id'];
                $drug[$k]['medicine_name'] = $v['medicine_name'];
                $drug[$k]['specification'] = $v['specification'];
                $drug[$k]['count'] = $v['counts'];
                $drug[$k]['unit'] = $v['unit'];
                $drug[$k]['msg'] = $v['msg'];
                $drug[$k]['price'] = $v['sell'];
                $drug[$k]['total'] = $v['sell']*$v['counts'];
                $drug[$k]['create_time'] = time();
            }

            //新增药品单表
            $insert_drug = Db::table('fa_drug')
                ->insertAll($drug);
        }else{
            $insert_drug = 1;
        }

        //判断会员数据是否为空
        if (!empty($arr['vip'])){
            //组装会员单数据
            foreach ($arr['vip'] as $k=>$v){
                $vip[$k]['order_id'] = $insert;
                $vip[$k]['serve_id'] = $v['id'];
                $vip[$k]['serve_name'] = $v['name'];
                $vip[$k]['count'] = $v['counts'];
                $vip[$k]['units'] = $v['units'];
                $vip[$k]['msg'] = $v['msg'];
                $vip[$k]['price'] = $v['price'];
                $vip[$k]['total'] = $v['price']*$v['counts'];
                $vip[$k]['create_time'] = time();
            }

            //新增药品单表
            $insert_vip = Db::table('fa_serve')
                ->insertAll($vip);
        }else{
            $insert_vip = 1;
        }

        //判断体检项目数据是否为空
        if (!empty($arr['health'])){
            //组装会员单数据
            foreach ($arr['health'] as $k=>$v){
                $health[$k]['order_id'] = $insert;
                $health[$k]['health_id'] = $v['id'];
                $health[$k]['health_name'] = $v['name'];
                $health[$k]['msg'] = $v['msg'];
                $health[$k]['price'] = $v['price'];
                $health[$k]['create_time'] = time();
            }

            //新增体检项目表
            $insert_health = Db::table('fa_health_log')
                ->insertAll($health);
        }else{
            $insert_health = 1;
        }

        //判断评分数据是否为空
        if (!empty($arr['score'])){
            //组装评分表数据
            foreach ($arr['score'] as $k=>$v){
                $score[$k]['order_id'] = $insert;
                $score[$k]['name'] = $v['name'];
                $score[$k]['number'] = $v['number'];
                $score[$k]['total_points'] = $v['total_points'];
                $score[$k]['str'] = json_encode($v['str']);
                $score[$k]['date'] = date('Y-m-d');
                $score[$k]['create_time'] = time();
            }

            //新增评分表
            $insert_score = Db::table('fa_score')
                ->insertAll($score);
        }else{
            $insert_score = 1;
        }

        if (!empty($id)){
            //改变接诊单状态
            $update = Db::table('fa_registration')
                ->where('id',$id)
                ->update([
                    'status' => '已完成',
                    'update_time' => time(),
                ]);
        }else{
            $update = 1;
        }


        if (($update !== false)&& ($insert !== false) && ($insert_score !== false) && ($insert_diagnosis !== false) && ($insert_drug !== false) && ($insert_course !== false) && ($insert_vip !== false) && ($insert_health !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }

    }

    /**
     * 诊疗服务单列表接口
     *
     */
    public function diagnosis_listss(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $code = empty(request()->post('code')) ? '':request()->post('code');
        $info_name = empty(request()->post('info_name')) ? '':request()->post('info_name');
        $medic_name = empty(request()->post('medic_name')) ? '':request()->post('medic_name');
        $medic_id = empty(request()->post('medic_id')) ? '':request()->post('medic_id');

        $status = request()->post('status');

        if ($status === 0){
            $status = 0;
        }

        $assess = empty(request()->post('assess')) ? '':request()->post('assess');
        $create_begin = empty(request()->post('create_begin')) ? '':request()->post('create_begin');
        $create_end = empty(request()->post('create_end')) ? '':request()->post('create_end');
        //$serve_begin = empty(request()->post('serve_begin')) ? '':request()->post('serve_begin');
        //$serve_end = empty(request()->post('serve_end')) ? '':request()->post('serve_end');
        $serve_time = empty(request()->post('serve_time')) ? '':request()->post('serve_time');



        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        $wheres = [];
        $wheress = [];
        if (!empty($serve_time)){
            if ((!empty($create_begin)) && (!empty($create_end))){
                $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
                $wheress['a.create_time'] = ['<=',strtotime($create_end)];
            }

            if (!empty($code)){
                $where['a.code'] = ['like',"%".$code."%"];
            }

            if (!empty($info_name)){
                $where['b.name'] = ['like',"%".$info_name."%"];
            }

            if (!empty($medic_name)){
                $where['a.medic_name'] = ['like',"%".$medic_name."%"];
            }

            if (!empty($status)){
                $where['a.status'] = $status;
            }

            if (!empty($assess)){
                $where['a.assess'] = $assess;
            }

            if (!empty($medic_id)){
                $where['a.medic_id'] = $medic_id;
            }

            $data = Db::table('fa_treatment')
                ->alias('c')
                ->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time,a.medic_id')
                ->join('fa_diagnosis_order a','a.id=c.order_id','left')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where('c.date',$serve_time)
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_treatment')
                ->alias('c')
                //->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time')
                ->join('fa_diagnosis_order a','a.id=c.order_id','left')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where('c.date',$serve_time)
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->count();


            if (!empty($data)){
                foreach ($data as $k=>$v){
                    //0代表待缴费，1代表部分缴费，2代表缴费完成，3代表已关闭
                    switch ($v['status']){
                        case 0:
                            $data[$k]['status'] = '待缴费';
                            break;
                        case 1:
                            $data[$k]['status'] = '部分缴费';
                            break;
                        case 2:
                            $data[$k]['status'] = '缴费完成';
                            break;
                        case 3:
                            $data[$k]['status'] = '已关闭';
                            break;
                        default:
                            $data[$k]['status'] = '';
                            break;
                    }
                    $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }

        }else{

            if ((!empty($create_begin)) && (!empty($create_end))){
                $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
                $wheress['a.create_time'] = ['<=',strtotime($create_end)];
            }

            if (!empty($code)){
                $where['a.code'] = ['like',"%".$code."%"];
            }

            if (!empty($info_name)){
                $where['b.name'] = ['like',"%".$info_name."%"];
            }

            if (!empty($medic_name)){
                $where['a.medic_name'] = ['like',"%".$medic_name."%"];
            }

            if (!empty($status)){
                $where['a.status'] = $status;
            }

            if (!empty($assess)){
                $where['a.assess'] = $assess;
            }

            if (!empty($medic_id)){
                $where['a.medic_id'] = $medic_id;
            }

            $data = Db::table('fa_diagnosis_order')
                ->alias('a')
                ->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time,a.medic_id')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->limit($page_start,$limt)
                ->order('id','desc')
                ->select();

            $total = Db::table('fa_diagnosis_order')
                ->alias('a')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->count();

            if (!empty($data)){
                foreach ($data as $k=>$v){
                    //0代表待缴费，1代表部分缴费，2代表缴费完成，3代表已关闭
                    switch ($v['status']){
                        case 0:
                            $data[$k]['status'] = '待缴费';
                            break;
                        case 1:
                            $data[$k]['status'] = '部分缴费';
                            break;
                        case 2:
                            $data[$k]['status'] = '缴费完成';
                            break;
                        case 3:
                            $data[$k]['status'] = '已关闭';
                            break;
                        default:
                            $data[$k]['status'] = '';
                            break;
                    }
                    $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }

        }

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $count = Db::table('fa_treatment')
                    ->where('order_id',$v['id'])
                    ->count();

                $counta = Db::table('fa_treatment')
                    ->where(['order_id'=>$v['id'],'finish'=>1])
                    ->count();

                $data[$k]['other'] = $counta.'/'.$count;
                $data[$k]['serve'] = Db::table('fa_treatment')
                    ->field('date')
                    ->where('order_id',$v['id'])
                    ->order('date','desc')
                    ->select();
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);
    }

    /**
     * 诊疗服务单详情接口
     *
     */
    public function diagnosis_details(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.id,a.code,a.assess,a.info_id,b.name,b.number,b.user_id,b.sex,b.birthday,b.mobile,a.disease_ids,a.disease_name,a.medic_name,a.nurse_name,a.height,a.weight,a.blood_pressure,a.sphygmus,a.disease_ids,a.disease_name,a.appeal,a.now,a.before,a.physique,a.diagnose,a.treatment,a.announcements,a.msg,a.remote_views,a.type,a.status,b.address,a.diagnosis_cost,a.drugs_cost,a.vip_cost,a.symptom,a.other_cost,a.new_str,a.new_price,a.count_cost,a.vip_discounts,a.vip_deduction,a.iscounts_cost,a.check_code,a.reality_cost,a.on_account,a.pay,a.is_signature,a.signature,a.diagnosis_msgs,a.drug_msgs')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where('a.id',$id)
            ->find();

        if (!empty($data)){
            //$data['receivable'] = number_format($data['count_cost']+$data['other_cost']-$data['vip_discounts']-$data['iscounts_cost']-$data['vip_deduction'],2,'.','');
            $data['receivable'] = number_format($data['count_cost']+$data['other_cost']-$data['vip_discounts']-$data['iscounts_cost']-$data['vip_deduction']+($data['new_price']),2,'.','');

            $data['disease_ids'] = explode(',',$data['disease_ids']);
            $data['age'] = countage($data['birthday']);

            if (!empty($data['new_str'])){
                $data['new_str'] = $data['new_str'].':'.$data['new_price'];
            }

            //1代表转账，2代表现金，3代表pos机，4代表支付宝，5代表微信，6代表储值卡，7代表积分
            switch ($data['pay']){
                case 1:
                    $data['pay'] = '转账';
                    break;
                case 2:
                    $data['pay'] = '现金';
                    break;
                case 3:
                    $data['pay'] = 'pos机';
                    break;
                case 4:
                    $data['pay'] = '支付宝';
                    break;
                case 5:
                    $data['pay'] = '微信';
                    break;
                case 6:
                    $data['pay'] = '储值卡';
                    break;
                case 7:
                    $data['pay'] = '积分';
                    break;
                default:
                    $data['pay'] = '无';
                    break;
            }


            //诊疗单数据
            $data['diagnosis_arrs'] = Db::table('fa_diagnosiss')
                ->where('order_id',$data['id'])
                ->select();

            if (!empty($data['diagnosis_arrs'])){
                foreach ($data['diagnosis_arrs'] as $k=>$v){
                    $data['diagnosis_arrs'][$k]['counts'] = $v['count'];
                    $data['diagnosis_arrs'][$k]['name'] = $v['diagnosis_name'];
                    $data['diagnosis_arrs'][$k]['id'] = $v['diagnosis_id'];
                }
            }
            //药品单数据
            $data['drug_arr'] = Db::table('fa_drug')
                ->where('order_id',$data['id'])
                ->select();

            if (!empty($data['drug_arr'])){
                foreach ($data['drug_arr'] as $k=>$v){
                    $data['drug_arr'][$k]['counts'] = $v['count'];
                    $data['drug_arr'][$k]['sell'] = $v['price'];
                    $data['drug_arr'][$k]['id'] = $v['medicine_id'];

//                    $count = Db::table('fa_medicine')
//                        ->where('id',$v['medicine_id'])
//                        ->find();

                    $count = Db::table('fa_storage')
                        ->where('id',$v['medicine_id'])
                        ->find();
                    if (!empty($count)){
                        $data['drug_arr'][$k]['count'] = $count['quantity'];
                    }else{
                        $data['drug_arr'][$k]['count'] = 0;
                    }


                }
            }

            //会员服务数据
            $data['vip_arr'] = Db::table('fa_serve')
                ->where('order_id',$data['id'])
                ->select();

            if (!empty($data['vip_arr'])){
                foreach ($data['vip_arr'] as $k=>$v){
                    $data['vip_arr'][$k]['counts'] = $v['count'];
                    $data['vip_arr'][$k]['name'] = $v['serve_name'];
                }
            }

            //会员服务数据
            $data['health_arr'] = Db::table('fa_health_log')
                ->field('id,health_name,price,msg')
                ->where('order_id',$data['id'])
                ->select();

            //疗程数据
            $data['diagnosis_arr'] = Db::table('fa_treatment')
                ->where('order_id',$data['id'])
                ->select();

            //评分数据
            $data['score_arr'] = Db::table('fa_score')
                ->field('id,name,date,number,total_points,str')
                ->where('order_id',$data['id'])
                ->select();

            if (!empty($data['score_arr'])){
                foreach ($data['score_arr'] as $k=>$v){
                    $data['score_arr'][$k]['str'] = json_decode($v['str'],true);
                }
            }

        }

        $this->success('成功',$data);
    }

    /**
     *疗效评估修改
     *
     */
    public function assess(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $assess = empty(request()->post('assess')) ? $this->error('assess不能为空'):request()->post('assess');

        $update = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->update([
                'assess' => $assess,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败');
        }

    }

    /**
     * 会员健康档案列表
     *
     */
    public function vip_record(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数


        $name = empty(request()->post('name')) ? '':request()->post('name');
        $sex = empty(request()->post('sex')) ? '':request()->post('sex');
        $mobile = empty(request()->post('mobile')) ? '':request()->post('mobile');
        $id_card = empty(request()->post('id_card')) ? '':request()->post('id_card');
        $level = empty(request()->post('level')) ? '':request()->post('level');
        $vip = empty(request()->post('vip')) ? '':request()->post('vip');
        $create_begin = empty(request()->post('create_begin')) ? '':request()->post('create_begin');
        $create_end = empty(request()->post('create_end')) ? '':request()->post('create_end');

        $status = empty(request()->post('status')) ? '':request()->post('status');

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        $wheres = [];
        $wheress = [];


        if ((!empty($create_begin)) && (!empty($create_end))){
            $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
            $wheress['a.create_time'] = ['<=',strtotime($create_end)];
        }

        if (!empty($name)){
            $where['a.name'] = ['like',"%".$name."%"];
        }

        if (!empty($sex)){
            $where['a.sex'] = $sex;
        }

        if (!empty($mobile)){
            $where['a.mobile'] = ['like',"%".$mobile."%"];
        }

        if (!empty($id_card)){
            $where['a.id_card'] = ['like',"%".$id_card."%"];
        }

        if (!empty($level)){
            $where['b.level'] = $level;
        }

        if (!empty($vip)){
            $where['b.vip'] = $vip;
        }

        if (!empty($status)){
            $where['a.status'] = 0;
        }

        $data = Db::table('fa_info')
            ->alias('a')
            ->field('a.id,a.name,b.level,a.sex,a.birthday,a.id_card,a.mobile,a.create_time,a.number,a.status,b.vip,a.position,a.image')
            ->join('fa_users b','a.user_id=b.id','left')
            ->where($where)
            ->where($wheres)
            ->where($wheress)
            ->limit($page_start,$limt)
            ->order('id','desc')
            ->select();

        $total = Db::table('fa_info')
            ->alias('a')
            //->field('a.id,a.name,b.level,a.sex,a.birthday,a.id_card,a.mobile,a.create_time')
            ->join('fa_users b','a.user_id=b.id','left')
            ->where($where)
            ->where($wheres)
            ->where($wheress)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['age'] = countage($v['birthday']);
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                $level_arr = Db::table('fa_vip_level')
                    ->where('id',$v['level'])
                    ->find();
                if (!empty($level_arr)){
                    $data[$k]['level_name'] = $level_arr['level_name'];
                }else{
                    $data[$k]['level_name'] = '';
                }

                $card_arr = Db::table('fa_vip_card')
                    ->where('id',$v['vip'])
                    ->find();

                if (!empty($card_arr)){
                    $data[$k]['vip_name'] = $card_arr['name'];
                }else{
                    $data[$k]['vip_name'] = '';
                }

            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);


    }

    /**
     * 会员档案-基础信息
     *
     */
    public function basic_information(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_info')
            ->alias('a')
            ->field('a.id,a.name,b.level,a.sex,a.nation,a.relation,a.id_card,a.mobile,a.nationality,a.birthday,a.birthplace,a.address,b.vip,a.status,a.image,b.nickname,a.user_id')
            ->join('fa_users b','a.user_id=b.id','left')
            ->where('a.id',$id)
            ->find();

        if (!empty($data)){
            $data['age'] = countage($data['birthday']);

            $level_name = Db::table('fa_vip_level')
                ->where('level',$data['level'])
                ->find();

            if (!empty($level_name)){
                $data['level_name'] = $level_name['level_name'];
            }else{
                $data['level_name'] = '';
            }

            $card_name = Db::table('fa_vip_card')
                ->where('id',$data['vip'])
                ->find();

            if (!empty($card_name)){
                $data['level_name'] = $data['level_name'].'('.$card_name['name'].')';
            }

            unset($data['level']);

        }

        $this->success('成功',$data);
    }

    /**
     * 会员档案-健康信息
     *
     */
    public function health_information(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_diagnosis_order')
            ->field('id,code,medic_id,medic_name,create_time,height,weight,blood_pressure,sphygmus,disease_ids,disease_name,appeal,now,before,physique,diagnose,treatment,announcements,msg,remote_views,type,status,diagnosis_msgs,drug_msgs')
            ->where('info_id',$id)
            ->order('id','desc')
            ->select();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                $data[$k]['score'] = Db::table('fa_score')
                    ->field('id,name,date,number')
                    ->where('order_id',$v['id'])
                    ->order('date','desc')
                    ->select();

                $data[$k]['diagnosis'] = Db::table('fa_diagnosiss')
                    ->where('order_id',$v['id'])
                    ->select();

                $data[$k]['drug'] = Db::table('fa_drug')
                    ->where('order_id',$v['id'])
                    ->select();

                //$data[$k]['vip'] = Db::table('fa_serve')
                    //->where('order_id',$v['id'])
                    //->select();
            }
        }


        $this->success('成功',$data);

    }

    /**
     * 新增评分表
     *
     */
    public function add_score(){
        $order_id = empty(request()->post('order_id')) ? $this->error('order_id不能为空'):request()->post('order_id');
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');
        $number = empty(request()->post('number')) ? $this->error('number不能为空'):request()->post('number');
        $total_points = empty(request()->post('total_points')) ? $this->error('total_points不能为空'):request()->post('total_points');
        //$str = empty(request()->post('str')) ? $this->error('str不能为空'):request()->post('str');
        $str = empty(input('post.str/a')) ? $this->error('str不能为空'):input('post.str/a');


        $score = [];
        //组装评分表数据
        $score['order_id'] = $order_id;
        $score['name'] = $name;
        $score['number'] = $number;
        $score['total_points'] = $total_points;
        $score['str'] = json_encode($str);
        $score['date'] = date('Y-m-d');
        $score['create_time'] = time();


        //新增评分表
        $insert_score = Db::table('fa_score')
            ->insertGetId($score);

        if ($insert_score > 0){
            $this->success('成功',$insert_score);
        }else{
            $this->error('失败');
        }
    }

    /**
     *
     * 编辑诊疗服务单
     */
    public function edit_order(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $arr = empty(input('post.arr/a')) ? $this->error('arr不能为空'):input('post.arr/a');

        $pan = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->find();

        if (empty($pan)){
            $this->error('服务单数据为空');
        }

        if($this->user_arr['id'] != $pan['medic_id']){
            $this->error('不是该服务单专家,不能修改!');
        }

        if (empty($arr['diagnosis_msgs'])){
            $diagnosis_msgs = '';
        }else{
            $diagnosis_msgs = $arr['diagnosis_msgs'];
        }

        if (empty($arr['drug_msgs'])){
            $drug_msgs = '';
        }else{
            $drug_msgs = $arr['drug_msgs'];
        }


        //开启事务
        Db::startTrans();

        //新增诊疗订单表
        $update = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->update([
                //'medic_id' => $this->user_arr['id'],
                //'medic_name' => $this->user_arr['name'],
                'height' => $arr['physique']['height'],
                'weight' => $arr['physique']['weight'],
                'blood_pressure' => $arr['physique']['blood_pressure'],
                'sphygmus' => $arr['physique']['sphygmus'],
                'disease_ids' => $arr['other']['disease_ids'],
                'disease_name' => $arr['other']['disease_name'],
                'appeal' => $arr['medical']['appeal'],
                'now' => $arr['medical']['now'],
                'before' => $arr['medical']['before'],
                'physique' => $arr['medical']['physique'],
                'diagnose' => $arr['medical']['diagnose'],
                'treatment' => $arr['medical']['treatment'],
                'announcements' => $arr['medical']['announcements'],
                'msg' => $arr['medical']['msg'],
                'remote_views' => $arr['medical']['remote_views'],
                'update_time' => time(),
                'type' => $arr['other']['type'],
                'diagnosis_cost' => $arr['other']['diagnosis_cost'],
                'drugs_cost' => $arr['other']['drugs_cost'],
                'vip_cost' => $arr['other']['vip_cost'],
                'count_cost' => $arr['other']['count_cost'],
                'symptom' => $arr['other']['symptom'],
                'health_money' => $arr['other']['health_money'],
                'diagnosis_msgs' => $diagnosis_msgs,
                'drug_msgs' => $drug_msgs,
            ]);


        //判断诊疗单数据是否为空
        if (!empty($arr['diagnosis'])){
            $diagnosis_del = Db::table('fa_diagnosiss')
                ->where('order_id',$id)
                ->delete();

            if ($diagnosis_del !== false){
                //组装诊疗单数据
                foreach ($arr['diagnosis'] as $k=>$v){
                    $diagnosis[$k]['order_id'] = $id;
                    $diagnosis[$k]['diagnosis_id'] = $v['id'];
                    $diagnosis[$k]['diagnosis_name'] = $v['name'];
                    $diagnosis[$k]['specification'] = $v['specification'];
                    $diagnosis[$k]['count'] = $v['counts'];
                    $diagnosis[$k]['unit'] = $v['unit'];
                    $diagnosis[$k]['msg'] = $v['msg'];
                    $diagnosis[$k]['price'] = $v['price'];
                    $diagnosis[$k]['total'] = $v['price']*$v['counts'];
                    $diagnosis[$k]['create_time'] = time();
                }

                //新增诊疗单表
                $insert_diagnosis = Db::table('fa_diagnosiss')
                    ->insertAll($diagnosis);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('诊疗单数据删除失败');
            }

        }else{
            $diagnosis_del = Db::table('fa_diagnosiss')
                ->where('order_id',$id)
                ->delete();
            $insert_diagnosis = 1;
        }

        //判断药品单数据是否为空
        if (!empty($arr['drug'])){
            //判断药品库存
            foreach ($arr['drug'] as $k=>$v){
                $find = Db::table('fa_storage')
                    ->where(['id'=>$v['id']])
                    ->find();

                if (empty($find)){
                    $this->error(__($v['medicine_name'].'药品数据为空'));
                }

                if (($find['quantity']-$v['counts']) < 0){
                    $this->error(__($v['medicine_name'].'药品库存不足'));
                }
            }


            $drug_del = Db::table('fa_drug')
                ->where('order_id',$id)
                ->delete();

            if ($drug_del !== false){
                //组装药品单数据
                foreach ($arr['drug'] as $k=>$v){
                    $drug[$k]['order_id'] = $id;
                    $drug[$k]['medicine_id'] = $v['id'];
                    $drug[$k]['medicine_name'] = $v['medicine_name'];
                    $drug[$k]['specification'] = $v['specification'];
                    $drug[$k]['count'] = $v['counts'];
                    $drug[$k]['unit'] = $v['unit'];
                    $drug[$k]['msg'] = $v['msg'];
                    $drug[$k]['price'] = $v['sell'];
                    $drug[$k]['total'] = $v['sell']*$v['counts'];
                    $drug[$k]['create_time'] = time();
                }

                //新增药品单表
                $insert_drug = Db::table('fa_drug')
                    ->insertAll($drug);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('药品单数据删除失败');
            }

        }else{
            $drug_del = Db::table('fa_drug')
                ->where('order_id',$id)
                ->delete();
            $insert_drug = 1;
        }



        //判断疗程数据是否为空
        if (!empty($arr['course'])){
            $course_del = Db::table('fa_treatment')
                ->where('order_id',$id)
                ->delete();

            if ($course_del !== false){
                //组装疗程数据
                foreach ($arr['course'] as $k=>$v){
                    $course[$k]['order_id'] = $id;
                    $course[$k]['info_id'] = $pan['info_id'];
                    $course[$k]['name'] = '第'.($k+1).'次';
                    $course[$k]['date'] = $v['date'];
                    $course[$k]['create_time'] = time();
                }


                //新增疗程表
                $insert_course = Db::table('fa_treatment')
                    ->insertAll($course);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('疗程数据删除失败');
            }

        }else{
            $insert_course = 1;
        }


        //判断会员数据是否为空
        if (!empty($arr['vip'])){
            $vip_del = Db::table('fa_serve')
                ->where('order_id',$id)
                ->delete();

            if ($vip_del !== false){
                //组装会员单数据
                foreach ($arr['vip'] as $k=>$v){
                    $vip[$k]['order_id'] = $id;
                    $vip[$k]['serve_id'] = $v['id'];
                    $vip[$k]['serve_name'] = $v['name'];
                    $vip[$k]['count'] = $v['counts'];
                    $vip[$k]['units'] = $v['units'];
                    $vip[$k]['msg'] = $v['msg'];
                    $vip[$k]['price'] = $v['price'];
                    $vip[$k]['total'] = $v['price']*$v['counts'];
                    $vip[$k]['create_time'] = time();
                }

                //新增药品单表
                $insert_vip = Db::table('fa_serve')
                    ->insertAll($vip);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('会员数据删除失败');
            }

        }else{
            $vip_del = Db::table('fa_serve')
                ->where('order_id',$id)
                ->delete();
            $insert_vip = 1;
        }


        //判断体检项目数据是否为空
        if (!empty($arr['health'])){
            $health_del = Db::table('fa_health_log')
                ->where('order_id',$id)
                ->delete();

            if ($health_del !== false){
                //组装会员单数据
                foreach ($arr['health'] as $k=>$v){
                    $health[$k]['order_id'] = $id;
                    $health[$k]['health_id'] = $v['id'];
                    $health[$k]['health_name'] = $v['name'];
                    $health[$k]['price'] = $v['price'];
                    $health[$k]['msg'] = $v['msg'];
                    $health[$k]['create_time'] = time();
                }

                //新增体检项目表
                $insert_health = Db::table('fa_health_log')
                    ->insertAll($health);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('体检项目数据删除失败');
            }

        }else{
            $health_del = Db::table('fa_health_log')
                ->where('order_id',$id)
                ->delete();
            $insert_health = 1;
        }

        //判断评分数据是否为空
        if (!empty($arr['score'])){
            $score_del = Db::table('fa_score')
                ->where('order_id',$id)
                ->delete();

            if ($score_del !== false){
                //组装评分表数据
                foreach ($arr['score'] as $k=>$v){
                    $score[$k]['order_id'] = $id;
                    $score[$k]['name'] = $v['name'];
                    $score[$k]['number'] = $v['number'];
                    $score[$k]['total_points'] = $v['total_points'];
                    $score[$k]['str'] = json_encode($v['str']);
                    $score[$k]['date'] = date('Y-m-d');
                    $score[$k]['create_time'] = time();
                }

                //新增评分表
                $insert_score = Db::table('fa_score')
                    ->insertAll($score);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('评分表数据删除失败');
            }

        }else{
            $insert_score = 1;
        }


        if (($update !== false) && ($insert_diagnosis > 0) && ($insert_drug > 0) && ($insert_course > 0) && ($insert_vip > 0) && ($insert_score > 0) && ($insert_health !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }

    }

    /**
     * 新增报告
     *
     */
    public function add_report(){
        $type = empty(request()->post('type')) ? '':request()->post('type');
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $arr = empty(input('post.arr/a')) ? $this->error('arr不能为空'):input('post.arr/a');


        //开启事务
        Db::startTrans();

        $code = get_strings(8,2);

        if (!empty($type)){
            $insert = Db::table('fa_report')
                ->insertGetId([
                    'order_id' => $id,
                    'code' => $code,
                    'admin_id' => $this->user_arr['id'],
                    'type' => 1,
                    'create_time' => time(),
                ]);
        }else{
            $insert = Db::table('fa_report')
                ->insertGetId([
                    'order_id' => $id,
                    'code' => $code,
                    'salesman_id' => $this->user_arr['id'],
                    'salesman_name' => $this->user_arr['name'],
                    'create_time' => time(),
                ]);
        }

        $insert_arr = [];
        foreach ($arr as $k=>$v){
            $insert_arr[$k]['report_id'] = $insert;
            $insert_arr[$k]['title'] = $v['title'];
            $insert_arr[$k]['check_time'] = $v['check_time'];
            $insert_arr[$k]['image'] = $v['image'];
            $insert_arr[$k]['video'] = $v['video'];
            $insert_arr[$k]['file'] = $v['file'];
            $insert_arr[$k]['create_time'] = time();
        }

            //新增评分表
            $insert_log = Db::table('fa_report_log')
                ->insertAll($insert_arr);

        if (($insert > 0) && ($insert_log > 0)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }
    }

    /**
     * 查看-报告信息
     *
     */
    public function report_list(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $data = Db::table('fa_report')
            ->where('order_id',$id)
            ->order('id','desc')
            ->select();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['type_name'] = '';
                //$data[$k]['log_id'] = 0;

                if ($v['type'] == 1){
                    $data[$k]['type_name'] = '健康顾问';

                    $salesman_arr = Db::table('fa_admin')
                        ->where('id',$v['admin_id'])
                        ->find();

                    if (empty($salesman_arr)){
                        $data[$k]['salesman_name'] = '';
                    }else{
                        $data[$k]['salesman_name'] = $salesman_arr['nickname'];
                    }
                }else{
                    $salesman_arr = Db::table('fa_medic')
                        ->where('id',$v['salesman_id'])
                        ->find();

                    if (empty($salesman_arr)){
                        $data[$k]['salesman_name'] = '';
                    }else{

                        $data[$k]['type_name'] = $salesman_arr['type'];
                        $data[$k]['salesman_name'] = $salesman_arr['name'];
                    }
                }


                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                $logs_arr = Db::table('fa_report_log')
                    ->field('id,title,check_time,image,video,file')
                    ->where('report_id',$v['id'])
                    ->select();

                $image_arr = [];
                $images_arr = [];

                $video_arr = [];
                $videos_arr = [];

                $file_arr = [];
                $files_arr = [];
                $i = 0;

                if (!empty($logs_arr)){
                    foreach ($logs_arr as $ks=>$vs){
                        $i += 100;
                        $image_arr = explode(';',$vs['image']);
                        if (!empty($image_arr)){
                            foreach ($image_arr as $ki=>$vi){
                                if (!empty($vi)){
                                    $images_arr[$ki+1000+$i]['id'] = $vs['id'];
                                    $images_arr[$ki+1000+$i]['image'] = $vi;
                                    $images_arr[$ki+1000+$i]['title'] = $vs['title'];
                                    $images_arr[$ki+1000+$i]['check_time'] = $vs['check_time'];
                                    $images_arr[$ki+1000+$i]['suffix'] = substr(strrchr($vi, '.'), 1);
                                }
                            }
                        }

                        $video_arr = explode(';',$vs['video']);

                        if (!empty($video_arr)){
                            foreach ($video_arr as $ki=>$vi){

                                if (!empty($vi)){
                                    $videos_arr[$ki+1000+$i]['id'] = $vs['id'];
                                    $videos_arr[$ki+1000+$i]['video'] = $vi;
                                    $videos_arr[$ki+1000+$i]['title'] = $vs['title'];
                                    $videos_arr[$ki+1000+$i]['check_time'] = $vs['check_time'];
                                    $videos_arr[$ki+1000+$i]['suffix'] = substr(strrchr($vi, '.'), 1);
                                }
                            }
                        }

                        $file_arr = explode(';',$vs['file']);
                        if (!empty($file_arr)){
                            foreach ($file_arr as $ki=>$vi){
                                if (!empty($vi)){
                                    $files_arr[$ki+1000+$i]['id'] = $vs['id'];
                                    $files_arr[$ki+1000+$i]['file'] = $vi;
                                    $files_arr[$ki+1000+$i]['title'] = $vs['title'];
                                    $files_arr[$ki+1000+$i]['check_time'] = $vs['check_time'];
                                    $files_arr[$ki+1000+$i]['suffix'] = substr(strrchr($vi, '.'), 1);
                                }
                            }
                        }

                    }

                    $data[$k]['image'] = array_merge($images_arr);
                    $data[$k]['video'] = array_merge($videos_arr);
                    $data[$k]['file'] = array_merge($files_arr);
                    //$data[$k]['log_id'] = $vs['id'];
                }

            }

        }

        $this->success('成功',$data);
    }


    /**
     *待确认药品单列表
     *
     */
    public function confirmed_list(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $status = request()->post('confirmed');

        $info_name = empty(request()->post('info_name')) ? '':request()->post('info_name');
        $create_begin = empty(request()->post('create_begin')) ? '':request()->post('create_begin');
        $create_end = empty(request()->post('create_end')) ? '':request()->post('create_end');



        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        $wheres = [];
        $wheress = [];

        if ((!empty($create_begin)) && (!empty($create_end))){
            $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
            $wheress['a.create_time'] = ['<=',strtotime($create_end)];
        }


        if (!empty($info_name)){
            $where['b.name'] = ['like',"%".$info_name."%"];
        }



        if (isset($status)){
            if ($status != ''){
                $where['a.confirmed'] = $status;
            }

        }



        $data = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.id,a.code,b.name,b.sex,b.birthday,a.medic_name,a.confirmed,a.create_time,a.status')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where($where)
            ->where($wheres)
            ->where($wheress)
            ->limit($page_start,$limt)
            ->order('id','desc')
            ->select();

        $total = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where($where)
            ->where($wheres)
            ->where($wheress)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                $data[$k]['age'] = countage($v['birthday']);
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);

    }

    /**
     * 新增耗材接口
     *
     */
    public function add_confirmed(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $arr = empty(input('post.arr/a')) ? '':input('post.arr/a');


        $order_arr = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->find();

        if (empty($order_arr)){
            $this->error('服务单不存在');
        }

        //开启事务
        Db::startTrans();
        $drug = [];
        $int = 0;
        $drugs_cost = 0;

        //判断药品单数据是否为空
        if (!empty($arr)){

            //判断药品库存
            foreach ($arr as $k=>$v){
                if (isset($v['ids'])){
                    $find = Db::table('fa_storage')
                        ->where(['id'=>$v['ids']])
                        ->find();
                }else{
                    $find = Db::table('fa_storage')
                        ->where(['id'=>$v['id']])
                        ->find();
                }


                if (empty($find)){
                    $this->error(__($v['medicine_name'].'药品数据为空'));
                }

                if (($find['quantity']-$v['counts']) < 0){
                    $this->error(__($v['medicine_name'].'药品库存不足'));
                }
            }


            $drug_del = Db::table('fa_drug')
                ->where('order_id',$id)
                ->delete();

            if ($drug_del !== false){
                //组装药品单数据
                foreach ($arr as $k=>$v){
                    if (isset($v['ids'])){
                        $medicine_ids = $v['ids'];
                    }else{
                        $medicine_ids = $v['id'];
                    }

                    $drug[$k]['order_id'] = $id;
                    $drug[$k]['medicine_id'] = $medicine_ids;
                    $drug[$k]['medicine_name'] = $v['medicine_name'];
                    $drug[$k]['specification'] = $v['specification'];
                    $drug[$k]['count'] = $v['counts'];
                    $drug[$k]['unit'] = $v['unit'];
                    $drug[$k]['msg'] = $v['msg'];
                    $drug[$k]['price'] = $v['sell'];
                    $drug[$k]['total'] = $v['sell']*$v['counts'];
                    $drug[$k]['create_time'] = time();

                    $drugs_cost += $v['sell']*$v['counts'];
                }
                //新增药品单表
                $insert_drug = Db::table('fa_drug')
                    ->insertAll($drug);
            }else{
                //事务回滚
                Db::rollback();
                $this->error('药品单数据删除失败');
            }

        }else{
            $dury_arr = Db::table('fa_drug')
                ->where('order_id',$id)
                ->select();

            if (!empty($dury_arr)){
                foreach ($dury_arr as $k=>$v){
                    $find = Db::table('fa_storage')
                        ->where(['id'=>$v['medicine_id']])
                        ->find();

                    if (empty($find)){
                        $this->error(__($v['medicine_name'].'药品数据为空'));
                    }

                    if (($find['quantity']-$v['count']) < 0){
                        $this->error(__($v['medicine_name'].'药品库存不足'));
                    }
                }
            }

            $insert_drug = 1;
            $drug_del = Db::table('fa_drug')
                ->where('order_id',$id)
                ->delete();

            if ($drug_del === false){
                //事务回滚
                Db::rollback();
                $this->error('药品单数据删除失败');
            }
        }

        $update = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->update([
                'drugs_cost' => $drugs_cost,
                'count_cost' => $order_arr['count_cost']-$order_arr['drugs_cost']+$drugs_cost,
                'confirmed' => 1,
                'update_time' => time(),
                'nurse_id' => $this->user_arr['id'],
                'nurse_name' => $this->user_arr['name'],
            ]);


        if (($update !== false) && ($insert_drug !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }

    }

    /**
     * 护士工作台
     *
     */
    public function nurse_alert(){
        $begin_month = date('Y-m-01', strtotime(date("Y-m-d")));
        $end_month = date('Y-m-d', strtotime("$begin_month +1 month -1 day"));

        $seven_day = date('Y-m-d', strtotime(" +6 day"));

        $last_month = date('Y-m-01', strtotime('-1 month'));
        $last_months = date('Y-m-t', strtotime('-1 month'));


        //这个月待处理数量
        $pending = Db::table('fa_treatment')
            ->alias('a')
            ->join('fa_diagnosis_order b','a.order_id=b.id','left')
            ->where(['a.finish'=>0,'b.status'=>['in',[1,2]]])
            ->where('a.date','between time',[$begin_month,$end_month])
            ->group('b.id')
            ->count();

        //本月待确认药品数量
        $drug = $data = Db::table('fa_diagnosis_order')
            ->where(['create_time'=>['>=',strtotime($begin_month)],'confirmed'=>0])
            ->where('create_time','<=',strtotime("$begin_month +1 month -1 day"))
            ->count();

        //今日治疗人数
        $today = Db::table('fa_treatment')
            ->alias('a')
            ->join('fa_diagnosis_order b','a.order_id=b.id','left')
            ->where(['a.finish'=>1,'a.date'=>date('Y-m-d'),'b.status'=>['in',[1,2]]])
            ->count();

        //近7天治疗人数
        $seven = Db::table('fa_treatment')
            ->alias('a')
            ->join('fa_diagnosis_order b','a.order_id=b.id','left')
            ->where(['a.finish'=>1,'a.date'=>['>=',date('Y-m-d')],'b.status'=>['in',[1,2]]])
            ->where(['a.date'=>['<=',$seven_day]])
            ->group('b.id')
            ->count();

        //本月治疗人数
        $month = Db::table('fa_treatment')
            ->alias('a')
            ->join('fa_diagnosis_order b','a.order_id=b.id','left')
            ->where(['a.finish'=>1,'a.date'=>['>=',$begin_month],'b.status'=>['in',[1,2]]])
            ->where(['a.date'=>['<=',$end_month]])
            ->group('b.id')
            ->count();

        //上月治疗人数
        $months = Db::table('fa_treatment')
            ->alias('a')
            ->join('fa_diagnosis_order b','a.order_id=b.id','left')
            ->where(['a.finish'=>1,'a.date'=>['>=',$last_month],'b.status'=>['in',[1,2]]])
            ->where(['a.date'=>['<=',$last_months]])
            ->group('b.id')
            ->count();

        $arr = [
            'pending' => $pending,
            'pending_begin' => $begin_month,
            'pending_end' => $end_month,
            'today' => $today,
            'today_time' => date('Y-m-d'),
            'seven' => $seven,
            'seven_begin' => date('Y-m-d'),
            'seven_end' => $seven_day,
            'month' => $month,
            'month_begin' => $begin_month,
            'month_end' => $end_month,
            'last_month' => $months,
            'last_begin' => $last_month,
            'last_end' => $last_months,
            'drug' => $drug,
            'drug_begin' => $begin_month,
            'drug_end' => $end_month,
        ];

        $this->success('成功',$arr);
    }


    /**
     * 专家工作台
     *
     */
    public function specialist_alert(){
        $three_day = date('Y-m-d', strtotime(" +2 day"));
        $seven_day = date('Y-m-d', strtotime(" +6 day"));

        $begin_month = date('Y-m-01', strtotime(date("Y-m-d")));
        $end_month = date('Y-m-d', strtotime("$begin_month +1 month -1 day"));

        $last_month = date('Y-m-01', strtotime('-3 month'));

        //预约上午人数
        $forenoon = Db::table('fa_registration')
            ->alias('a')
            ->field('a.id')
            ->join('fa_working b','a.working_id=b.id','left')
            ->where(['b.time'=>['<=',3],'a.medic_id'=>$this->user_arr['id'],'a.status'=>'待就诊','a.date'=>date('Y-m-d')])
            ->count();

        //预约下午人数
        $afternoon = Db::table('fa_registration')
            ->alias('a')
            ->join('fa_working b','a.working_id=b.id','left')
            ->where(['b.time'=>['>',3],'a.medic_id'=>$this->user_arr['id'],'a.status'=>'待就诊','a.date'=>date('Y-m-d')])
            ->count();

        //预约近3天人数
        $three = Db::table('fa_registration')
            ->alias('a')
            ->field('a.id')
            ->where(['a.medic_id'=>$this->user_arr['id'],'a.status'=>'待就诊','a.date'=>['<=',$three_day]])
            ->where(['a.date'=>['>=',date('Y-m-d')]])
            ->count();

        //预约近7天人数
        $seven = Db::table('fa_registration')
            ->alias('a')
            ->where(['a.medic_id'=>$this->user_arr['id'],'a.status'=>'待就诊','a.date'=>['<=',$seven_day]])
            ->where(['a.date'=>['>=',date('Y-m-d')]])
            ->count();

        //今日接诊人数
        $today = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->where(['a.medic_id'=>$this->user_arr['id'],'a.create_time'=>['<=',date('Y-m-d', strtotime(" +1 day"))]])
            ->where(['a.create_time'=>['>=',strtotime(date('Y-m-d'))]])
            ->count();

        //近7天接诊人数
        $sevens = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->field('a.id,a.create_time')
            ->where(['a.medic_id'=>$this->user_arr['id'],'a.create_time'=>['<=',strtotime($seven_day)]])
            ->where(['a.create_time'=>['>=',strtotime(date('Y-m-d'))]])
            ->count();

        //本月接诊人数
        $month = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->where(['a.medic_id'=>$this->user_arr['id'],'a.create_time'=>['<=',strtotime($end_month)]])
            ->where(['a.create_time'=>['>=',strtotime($begin_month)]])
            ->count();

        //本季度接诊人数
        $quarter = Db::table('fa_diagnosis_order')
            ->alias('a')
            ->where(['a.medic_id'=>$this->user_arr['id'],'a.create_time'=>['<=',strtotime($end_month)]])
            ->where(['a.create_time'=>['>=',strtotime($last_month)]])
            ->count();

        $arr = [
            'forenoon' => $forenoon,
            'forenoon_begin' => date('Y-m-d').' 09:00:00',
            'forenoon_end' => date('Y-m-d').' 12:00:00',
            'afternoon' => $afternoon,
            'afternoon_begin' => date('Y-m-d').' 12:00:00',
            'afternoon_end' => date('Y-m-d').' 18:00:00',
            'three' => $three,
            'three_begin' => date('Y-m-d'),
            'three_end' => $three_day.' 23:59:59',
            'seven' => $seven,
            'seven_begin' => date('Y-m-d'),
            'seven_end' => $seven_day.' 23:59:59',
            'today' => $today,
            'today_begin' => date('Y-m-d').' 00:00:00',
            'today_end' => date('Y-m-d').' 23:59:59',
            'sevens' => $sevens,
            'sevens_begin' => date('Y-m-d'),
            'sevens_end' => $seven_day.' 23:59:59',
            'month' => $month,
            'month_begin' => $begin_month,
            'month_end' => $end_month,
            'quarter' => $quarter,
            'quarter_begin' => $last_month,
            'quarter_end' => $end_month,
            'medic_id' => $this->user_arr['id'],
        ];

        $this->success('成功',$arr);
    }

    /**
     * 专家工作台-我的排班
     *
     */
    public function working_list(){
        //获取本周日期
        $week = get_week(time());
        foreach ($week as $k=>$v){
            $week[$k]['str'] = $v['date'].'('.$v['week'].')';
        }

        $data = [
            0 => [
                $week,
            ],
            1 => [
                $week,
            ],
            2 => [
                $week,
            ],
            3 => [
                $week,
            ],
            4 => [
                $week,
            ],
            5 => [
                $week,
            ],
        ];


        foreach ($data as $k=>$v){
            foreach ($v as $kk=>$vv){
                foreach ($vv as $kkk=>$vvv){
                    $datas = Db::table('fa_working')
                        ->alias('a')
                        ->field('a.id,b.name,a.medic_id')
                        ->join('fa_medic b','a.medic_id=b.id','left')
                        ->where(['a.date'=>$vvv['date'],'a.time'=>$k+1,'a.medic_id'=>$this->user_arr['id']])
                        ->select();

                    if (!empty($datas)){
                        $names = [];
                        $ids = [];
                        $idss = [];
                        foreach ($datas as $ks=>$vl){
                            $names[$ks] = $vl['name'];
                            $ids[$ks] = $vl['medic_id'];
                            $idss[$vl['medic_id']] = $vl['id'];
                        }

                        $data[$k][$kk][$kkk]['name'] = implode(',',$names);
                        $data[$k][$kk][$kkk]['ids'] = implode(',',$ids);
                    }else{
                        $data[$k][$kk][$kkk]['name'] = '';
                        $data[$k][$kk][$kkk]['ids'] = '';
                    }

                }

            }

        }

        $this->success('成功',$data);
    }

    /**
     * 诊疗服务单列表接口
     *
     */
    public function diagnosis_list(){
        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        $code = empty(request()->post('code')) ? '':request()->post('code');
        $info_name = empty(request()->post('info_name')) ? '':request()->post('info_name');
        $medic_name = empty(request()->post('medic_name')) ? '':request()->post('medic_name');
        $medic_id = empty(request()->post('medic_id')) ? '':request()->post('medic_id');

        $finish = request()->post('finish');

        $status = request()->post('status');


        $assess = empty(request()->post('assess')) ? '':request()->post('assess');
        $create_begin = empty(request()->post('create_begin')) ? '':request()->post('create_begin');
        $create_end = empty(request()->post('create_end')) ? '':request()->post('create_end');
        $serve_begin = empty(request()->post('serve_begin')) ? '':request()->post('serve_begin');
        $serve_end = empty(request()->post('serve_end')) ? '':request()->post('serve_end');
        $serve_time = empty(request()->post('serve_time')) ? '':request()->post('serve_time');



        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        $wheres = [];
        $wheress = [];
        if ((!empty($serve_begin)) && (!empty($serve_end))){
            if ((!empty($create_begin)) && (!empty($create_end))){
                $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
                $wheress['a.create_time'] = ['<=',strtotime($create_end)];
            }

            if (!empty($code)){
                $where['a.code'] = ['like',"%".$code."%"];
            }

            if (!empty($info_name)){
                $where['b.name'] = ['like',"%".$info_name."%"];
            }

            if (!empty($medic_name)){
                $where['a.medic_name'] = ['like',"%".$medic_name."%"];
            }


            if (!empty($assess)){
                $where['a.assess'] = $assess;
            }

            if (!empty($medic_id)){
                $where['a.medic_id'] = $medic_id;
            }

            if (isset($finish)){
                if (!empty($finish)){
                    $where['c.finish'] = $finish;
                }else {
                    if (is_numeric($finish)){
                        $where['c.finish'] = 0;
                    }
                }
            }


            if (isset($status)){
                if (!empty($status)){
                    if ($status == 4){
                        $where['a.status'] = ['in',[1,2]];
                    }else{
                        $where['a.status'] = $status;
                    }

                }else {
                    if (is_numeric($status)){
                        $where['a.status'] = 0;
                    }
                }
            }

            $data = Db::table('fa_treatment')
                ->alias('c')
                ->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time,a.medic_id,a.info_id,a.confirmed')
                ->join('fa_diagnosis_order a','a.id=c.order_id','left')
                ->join('fa_info b','a.info_id=b.id','left')
                //->where('c.date',$serve_time)
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->where('c.date', 'between time', [$serve_begin, $serve_end])
                ->group('a.id')
                ->limit($page_start,$limt)
                ->getLastSql();
//                ->select();

            $total = Db::table('fa_treatment')
                ->alias('c')
                //->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time')
                ->join('fa_diagnosis_order a','a.id=c.order_id','left')
                ->join('fa_info b','a.info_id=b.id','left')
                //->where('c.date',$serve_time)
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->where('c.date', 'between time', [$serve_begin, $serve_end])
                ->group('a.id')
                ->count();


            if (!empty($data)){
                foreach ($data as $k=>$v){
                    //0代表待缴费，1代表部分缴费，2代表缴费完成，3代表已关闭
                    switch ($v['status']){
                        case 0:
                            $data[$k]['status'] = '待缴费';
                            break;
                        case 1:
                            $data[$k]['status'] = '部分缴费';
                            break;
                        case 2:
                            $data[$k]['status'] = '缴费完成';
                            break;
                        case 3:
                            $data[$k]['status'] = '已关闭';
                            break;
                        default:
                            $data[$k]['status'] = '';
                            break;
                    }
                    $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }

        }elseif (!empty($serve_time)){
            if ((!empty($create_begin)) && (!empty($create_end))){
                $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
                $wheress['a.create_time'] = ['<=',strtotime($create_end)];
            }

            if (!empty($code)){
                $where['a.code'] = ['like',"%".$code."%"];
            }

            if (!empty($info_name)){
                $where['b.name'] = ['like',"%".$info_name."%"];
            }

            if (!empty($medic_name)){
                $where['a.medic_name'] = ['like',"%".$medic_name."%"];
            }


            if (!empty($assess)){
                $where['a.assess'] = $assess;
            }

            if (!empty($medic_id)){
                $where['a.medic_id'] = $medic_id;
            }


            if (isset($finish)){
                if (!empty($finish)){
                    $where['c.finish'] = $finish;
                }else {
                    if (is_numeric($finish)){
                        $where['c.finish'] = 0;
                    }
                }
            }


            if (isset($status)){
                if (!empty($status)){
                    if ($status == 4){
                        $where['a.status'] = ['in',[1,2]];
                    }else{
                        $where['a.status'] = $status;
                    }

                }else {
                    if (is_numeric($status)){
                        $where['a.status'] = 0;
                    }
                }
            }


            $data = Db::table('fa_treatment')
                ->alias('c')
                ->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time,a.medic_id,a.info_id,a.confirmed')
                ->join('fa_diagnosis_order a','a.id=c.order_id','left')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where('c.date',$serve_time)
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_treatment')
                ->alias('c')
                //->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time')
                ->join('fa_diagnosis_order a','a.id=c.order_id','left')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where('c.date',$serve_time)
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->count();


            if (!empty($data)){
                foreach ($data as $k=>$v){
                    //0代表待缴费，1代表部分缴费，2代表缴费完成，3代表已关闭
                    switch ($v['status']){
                        case 0:
                            $data[$k]['status'] = '待缴费';
                            break;
                        case 1:
                            $data[$k]['status'] = '部分缴费';
                            break;
                        case 2:
                            $data[$k]['status'] = '缴费完成';
                            break;
                        case 3:
                            $data[$k]['status'] = '已关闭';
                            break;
                        default:
                            $data[$k]['status'] = '';
                            break;
                    }
                    $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }
        }else{

            if ((!empty($create_begin)) && (!empty($create_end))){
                $wheres['a.create_time'] = ['>=',strtotime($create_begin)];
                $wheress['a.create_time'] = ['<=',strtotime($create_end)];
            }

            if (!empty($code)){
                $where['a.code'] = ['like',"%".$code."%"];
            }

            if (!empty($info_name)){
                $where['b.name'] = ['like',"%".$info_name."%"];
            }

            if (!empty($medic_name)){
                $where['a.medic_name'] = ['like',"%".$medic_name."%"];
            }

            if (isset($status)){
                if (!empty($status)){
                    if ($status == 4){
                        $where['a.status'] = ['in',[1,2]];
                    }else{
                        $where['a.status'] = $status;
                    }

                }else {
                    if (is_numeric($status)){
                        $where['a.status'] = 0;
                    }
                }
            }

            if (!empty($assess)){
                $where['a.assess'] = $assess;
            }

            if (!empty($medic_id)){
                $where['a.medic_id'] = $medic_id;
            }

            $data = Db::table('fa_diagnosis_order')
                ->alias('a')
                ->field('a.id,a.code,b.name,a.medic_name,a.status,a.create_time,a.medic_id,a.info_id,a.confirmed')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->limit($page_start,$limt)
                ->order('id','desc')
                ->select();

            $total = Db::table('fa_diagnosis_order')
                ->alias('a')
                ->join('fa_info b','a.info_id=b.id','left')
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->count();

            if (!empty($data)){
                foreach ($data as $k=>$v){
                    //0代表待缴费，1代表部分缴费，2代表缴费完成，3代表已关闭
                    switch ($v['status']){
                        case 0:
                            $data[$k]['status'] = '待缴费';
                            break;
                        case 1:
                            $data[$k]['status'] = '部分缴费';
                            break;
                        case 2:
                            $data[$k]['status'] = '缴费完成';
                            break;
                        case 3:
                            $data[$k]['status'] = '已关闭';
                            break;
                        default:
                            $data[$k]['status'] = '';
                            break;
                    }
                    $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
            }

        }

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $count = Db::table('fa_treatment')
                    ->where('order_id',$v['id'])
                    ->count();

                $counta = Db::table('fa_treatment')
                    ->where(['order_id'=>$v['id'],'finish'=>1])
                    ->count();

                $data[$k]['other'] = $counta.'/'.$count;
                $data[$k]['serve'] = Db::table('fa_treatment')
                    ->field('date')
                    ->where('order_id',$v['id'])
                    ->order('date','desc')
                    ->select();
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);
    }

    /**
     * 新增治疗日志
     *
     */
    public function add_log(){
        $type = empty(request()->post('type')) ? 0:request()->post('type');
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $date = empty(request()->post('date')) ? $this->error('date不能为空'):request()->post('date');
        $msg = empty(request()->post('msg')) ? $this->error('msg不能为空'):request()->post('msg');
        $image = empty(request()->post('image')) ? '':request()->post('image');

        $code = get_strings(8,2);

        if (!empty($type)){
            $insert = Db::table('fa_log')
                ->insertGetId([
                    'info_id' => $id,
                    'code' => $code,
                    'salesman_id' => $this->user_arr['id'],
                    'type' => $type,
                    'date' => $date,
                    'msg' => $msg,
                    'image' => $image,
                    'create_time' => time(),
                ]);
        }else{
            $insert = Db::table('fa_log')
                ->insertGetId([
                    'info_id' => $id,
                    'code' => $code,
                    'admin_id' => $this->user_arr['id'],
                    'type' => $type,
                    'date' => $date,
                    'msg' => $msg,
                    'image' => $image,
                    'create_time' => time(),
                ]);
        }

        if ($insert !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }


    }

    /**
     *治疗日志列表
     *
     */
    public function log_list(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $page = empty(request()->post('page')) ? 1:request()->post('page');//获取页码
        $limt = empty(request()->post('limt')) ? 10:request()->post('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $data = Db::table('fa_log')
            ->alias('a')
            ->field('a.id,a.code,a.date,a.msg,a.image,a.create_time,b.name,a.salesman_id,a.admin_id,a.type')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where('a.info_id',$id)
            ->limit($page_start,$limt)
            ->order('id','desc')
            ->select();

        $total = Db::table('fa_log')
            ->alias('a')
            ->join('fa_info b','a.info_id=b.id','left')
            ->where('a.info_id',$id)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                $data[$k]['type_name'] = '';
                $data[$k]['names'] = '';
                $data[$k]['images'] = [];
                $data[$k]['file'] = [];
                $data[$k]['video'] = [];
                if ($v['type'] != 0){
                    $type_name = Db::table('fa_admin')
                        ->field('id,nickname')
                        ->where('id',$v['salesman_id'])
                        ->find();
                    if (!empty($type_name)){
                        $data[$k]['names'] = $type_name['nickname'];
                    }
                    $data[$k]['type_name'] = '健康顾问';
                }else{
                    $type_name = Db::table('fa_medic')
                        ->field('id,name,type')
                        ->where('id',$v['admin_id'])
                        ->find();
                    if (!empty($type_name)){
                        $data[$k]['names'] = $type_name['name'];
                        $data[$k]['type_name'] = $type_name['type'];
                    }
                }

                if (!empty($v['image'])){
                    $image = explode(';',$v['image']);
                    if (!empty($image)){
                        foreach ($image as $kk=>$vv){
                            $suffix = substr(strrchr($vv, '.'), 1);
                            if (($suffix == 'jpg') || ($suffix == 'png') || ($suffix == 'jpeg')){
                                $data[$k]['images'][] = $vv;
                            }elseif ($suffix == 'mp4'){
                                $data[$k]['video'][] = $vv;
                            }else{
                                $data[$k]['file'][] = $vv;
                            }
                        }

                    }
                }


                unset($data[$k]['image']);
                unset($data[$k]['salesman_id']);
                unset($data[$k]['admin_id']);
                unset($data[$k]['type']);

            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('成功',$datas);

    }


    /**
     * 签字
     *
     */
    public function signature(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $img = empty(request()->post('img')) ? $this->error('img不能为空'):request()->post('img');

        $update = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->update([
                'is_signature' => 1,
                'signature' => $img,
                'update_time' => time(),
            ]);

        if ($update !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }
    }



    /**
     * 治疗日志详情
     *
     */
    public function get_log(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $data = Db::table('fa_log')
            ->field('id,date,msg,image')
            ->where('id',$id)
            ->find();

        if (!empty($data)){
            $data['images'] = [];
            $data['video'] = [];
            $data['file'] = [];
            if (!empty($data['image'])){
                $image = explode(';',$data['image']);
                if (!empty($image)){
                    foreach ($image as $kk=>$vv){
                        $suffix = substr(strrchr($vv, '.'), 1);
                        if (($suffix == 'jpg') || ($suffix == 'png') || ($suffix == 'jpeg')){
                            $data['images'][] = $vv;
                        }elseif ($suffix == 'mp4'){
                            $data['video'][] = $vv;
                        }else{
                            $data['file'][] = $vv;
                        }
                    }

                }
            }

            unset($data['image']);
        }

        $this->success('查询成功',$data);
    }


    /**
     * 编辑治疗日志
     *
     */
    public function edit_log(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $date = empty(request()->post('date')) ? $this->error('date不能为空'):request()->post('date');
        $msg = empty(request()->post('msg')) ? $this->error('msg不能为空'):request()->post('msg');
        $image = empty(request()->post('image')) ? '':request()->post('image');

        $insert = Db::table('fa_log')
            ->where('id',$id)
            ->update([
                'date' => $date,
                'msg' => $msg,
                'image' => $image,
                'update_time' => time(),
            ]);


        if ($insert !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }


    }

    /**
     * 删除治疗日志
     *
     */
    public function del_log(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $del = Db::table('fa_log')
            ->where('id',$id)
            ->delete();

        if ($del !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }
    }

    /**
     * 报告信息详情
     *
     */
    public function get_logs(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $logs_arr = Db::table('fa_report_log')
            ->field('id,title,check_time,image,video,file')
            ->where('report_id',$id)
            ->select();

        if (!empty($logs_arr)){
            foreach ($logs_arr as $k=>$v){
                if(!empty($v['image'])){
                    $logs_arr[$k]['image'] = $image = explode(';',$v['image']);
                }else{
                    $logs_arr[$k]['image'] = [];
                }

                if(!empty($v['video'])){
                    $logs_arr[$k]['video'] = $image = explode(';',$v['video']);
                }else{
                    $logs_arr[$k]['video'] = [];
                }

                if(!empty($v['file'])){
                    $logs_arr[$k]['file'] = $image = explode(';',$v['file']);
                }else{
                    $logs_arr[$k]['file'] = [];
                }

            }
        }


        $this->success('查询成功',$logs_arr);
    }


    /**
     * 编辑报告
     *
     */
    public function edit_report(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');
        $arr = empty(input('post.arr/a')) ? $this->error('arr不能为空'):input('post.arr/a');

        $report_arr = Db::table('fa_report')
            ->where('id',$id)
            ->find();

        if (empty($report_arr)){
            $this->error('报告数据为空');
        }

        //开启事务
        Db::startTrans();

        $del = Db::table('fa_report_log')
            ->where('report_id',$id)
            ->delete();

        if($del !== false){
            $insert_arr = [];
            foreach ($arr as $k=>$v){
                $insert_arr[$k]['report_id'] = $id;
                $insert_arr[$k]['title'] = $v['title'];
                $insert_arr[$k]['check_time'] = $v['check_time'];
                $insert_arr[$k]['image'] = $v['image'];
                $insert_arr[$k]['video'] = $v['video'];
                $insert_arr[$k]['file'] = $v['file'];
                $insert_arr[$k]['create_time'] = time();
            }

            //新增评分表
            $insert_log = Db::table('fa_report_log')
                ->insertAll($insert_arr);
        }else{
            $insert_log = 1;
        }


        if (($insert_log !== false)){
            //事务提交
            Db::commit();
            $this->success('成功');
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败');
        }
    }

    /**
     * 删除报告日志
     *
     */
    public function del_report(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        //开启事务
        Db::startTrans();
        $del = Db::table('fa_report')
            ->where('id',$id)
            ->delete();

        $log = Db::table('fa_report_log')
            ->where('report_id',$id)
            ->delete();

        if (($del !== false) && ($log !== false)){
            //事务提交
            Db::commit();
            $this->success('成功',[]);
        }else{
            //事务回滚
            Db::rollback();
            $this->error('失败',[]);
        }
    }

    /**
     * 新增看诊项目
     *
     */
    public function add_disease(){
        $name = empty(request()->post('name')) ? $this->error('name不能为空'):request()->post('name');

        $name_arr = explode(',',$name);
        $new_arr = [];
        foreach ($name_arr as $k=>$v){
            $pan_arr = Db::table('fa_disease')
                ->where('name',$v)
                ->find();

            if(!empty($pan_arr)){
                $this->error($v.',该看诊项目名称已存在');
            }

            $new_arr[] = [
                'name' => $v,
                'content' => '',
                'create_time' => time(),
            ];
        }

        $insert = Db::table('fa_disease')
            ->insertAll($new_arr);

        if ($insert !== false){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }

    /**
     * 删除诊疗服务单
     *
     */
    public function del_diagnosis(){
        $id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $order_arr = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->find();

        if (empty($order_arr)){
            $this->error('诊疗服务单数据为空',[]);
        }

        if (($order_arr['status'] == 1) || ($order_arr['status'] == 2)){
            $this->error('该订单已收费,不可删除',[]);
        }

        $del = Db::table('fa_diagnosis_order')
            ->where('id',$id)
            ->delete();

        if ($del !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败',[]);
        }



    }


}
